﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.Base;
using ERP.BusinessEntities;
using System.Data;
using Core;
using Utilities;

namespace MainApp.Modules.PO
{
    public class POEntity: BaseEntity
    {
        SGVList<APPOItemsInfo> lstAPPOItems = new SGVList<APPOItemsInfo>();

        public override void InitModuleObjects()
        {
            AddMainObject("APPOs", new APPOsInfo());
        }

        public override void InitLists()
        {
            base.InitLists();

            lstAPPOItems = new SGVList<APPOItemsInfo>();
            lstAPPOItems.InitList(this, "APPOs", "APPOItems", "FK_APPOs_ID");

            lstAPPOItems.Binding("MainScreen", "APPOItemsGridView");
        }

        public override void BeforeSaveList()
        {
            base.BeforeSaveList();

            APPOsInfo PO = (APPOsInfo)MainObject;
            if (PO == null) return;

            DataSet dsPOItems = AppContext.POItemCtrl.GetAllObjectByColumnValue("FK_APPOs_ID", PO.ID);
            if (dsPOItems != null && dsPOItems.Tables.Count > 0)
            {
                foreach (DataRow drPOItem in dsPOItems.Tables[0].Rows)
                {
                    APPOItemsInfo POItem = (APPOItemsInfo)AppContext.POItemCtrl.GetObjectFromDataRow(drPOItem);
                    if (POItem != null)
                        Inventory.UpdateInventory(InventoryDirection.Out, InventoryType.PO, POItem.FK_ICProducts_ID, POItem.FK_ICStocks_ID,
                            POItem.BatchNo, POItem.LotNo, POItem.SerialNo, POItem.Qty);

                }
            }

        }

        public override void AfterSaveList()
        {
            base.AfterSaveList();

            APPOsInfo PO = (APPOsInfo)MainObject;
            if (PO == null) return;

            DataSet dsPOItems = AppContext.POItemCtrl.GetAllObjectByColumnValue("FK_APPOs_ID", PO.ID);
            if (dsPOItems != null && dsPOItems.Tables.Count > 0)
            {
                foreach (DataRow drPOItem in dsPOItems.Tables[0].Rows)
                {
                    APPOItemsInfo POItem = (APPOItemsInfo)AppContext.POItemCtrl.GetObjectFromDataRow(drPOItem);
                    if (POItem != null)
                        Inventory.UpdateInventory(InventoryDirection.In, InventoryType.PO, POItem.FK_ICProducts_ID, POItem.FK_ICStocks_ID,
                            POItem.BatchNo, POItem.LotNo, POItem.SerialNo, POItem.Qty);

                }
            }

        }
    }
}
